package com.example.conf.base;

import com.example.exception.BusinessException;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

/**
 * ClassName: ResultBase
 * description: 响应结果基类
 *
 * @author wsy
 * @Date: 2022/11/20 12:07
 * @since JDK 1.8
 */
public class ResultBase<T> implements Serializable {

    private static final long serialVersionUID = 4457982953785948325L;

    @ApiModelProperty("是否成功")
    private boolean success;
    @ApiModelProperty("错误码")
    private String code;
    @ApiModelProperty("返回消息")
    private String message;
    @ApiModelProperty("返回数据")
    private T data;

    public T fetchDataIfSuccess() {
        if (this.success && "SUCCESS".equals(this.code)) {
            return this.data;
        } else {
            throw new BusinessException(this.message, this.code);
        }
    }

    public ResultBase() {
        this.setSuccess(true);
        this.setCode("SUCCESS");
        this.setMessage("成功");
    }

    public static ResultBase<Void> fail() {
        ResultBase<Void> result = new ResultBase();
        result.setSuccess(false);
        result.setCode("fail");
        result.setMessage("失败");
        return result;
    }
    public static ResultBase<Void> fail(String message) {
        ResultBase<Void> result = new ResultBase();
        result.setSuccess(false);
        result.setCode("fail");
        result.setMessage(message);
        return result;
    }

    public static ResultBase<Void> success() {
        ResultBase<Void> result = new ResultBase();
        result.setSuccess(true);
        result.setCode("SUCCESS");
        result.setMessage("成功");
        return result;
    }

    public static ResultBase<String> success(String message) {
        ResultBase<String> result = new ResultBase();
        result.setSuccess(true);
        result.setCode("SUCCESS");
        result.setMessage("成功");
        result.setData(message);
        return result;
    }

    public static <T> ResultBase<T> successData(T data) {
        ResultBase<T> result = new ResultBase();
        result.setSuccess(true);
        result.setCode("SUCCESS");
        result.setMessage("成功");
        result.setData(data);
        return result;
    }

    @Override
    public String toString() {
        return "ResultBase{message='" + this.message + '\'' + ", code='" + this.code + '\'' + ", success=" + this.success + ", data=" + this.data + '}';
    }

    public boolean isSuccess() {
        return this.success;
    }

    public String getCode() {
        return this.code;
    }

    public String getMessage() {
        return this.message;
    }

    public T getData() {
        return this.data;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setData(T data) {
        this.data = data;
    }
}
